<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>账户系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F9FAFB',
                            200: '#F3F4F6',
                            300: '#E5E7EB',
                            400: '#D1D5DB',
                            500: '#9CA3AF',
                            600: '#6B7280',
                            700: '#4B5563',
                            800: '#1F2937',
                            900: '#111827',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            /* 删除未使用的选择器 */
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
            }
            .btn-hover {
                @apply hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300;
            }
            /* 按钮样式优化 */
            button {
                @apply transition-colors duration-200;
            }

            /* 操作按钮间距 */
            td:last-child button {
                @apply mx-1;
            }

            /* 表格样式 */
            table {
                @apply w-full border-collapse;
            }
            th, td {
                @apply py-3 px-4 text-left;
            }
            th {
                @apply bg-neutral-100 font-semibold text-neutral-700;
            }
            tr:hover {
                @apply bg-neutral-50;
            }
            /* 响应式表格 */
            @media (max-width: 640px) {
                td, th {
                    @apply px-2 py-1 text-sm;
                }
            }

            /* 模态框样式 */
            .fixed {
                position: fixed;
            }
            .inset-0 {
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
            }
            .bg-opacity-50 {
                background-color: rgba(0, 0, 0, 0.5);
            }
            .z-50 {
                z-index: 50;
            }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen flex items-center justify-center p-4">
<div class="w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden">
    <!-- 登录表单 -->
    <div id="loginForm" class="p-8 md:p-10 space-y-8">
        <div class="text-center">
            <div class="text-[clamp(2rem,5vw,3rem)] text-primary mb-4">
                <i class="fa-solid fa-user-circle"></i>
            </div>
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-800">欢迎回来</h1>
            <p class="text-neutral-600 mt-2">请登录您的账户继续访问</p>
        </div>

        <form id="loginFormData" class="space-y-5">
            <div class="space-y-2">
                <label for="loginName" class="block text-sm font-medium text-neutral-700">姓名</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
                <i class="fa-solid fa-user"></i>
            </span>
                    <input type="text" id="loginName" name="username"
                    class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                    placeholder="请输入您的姓名" required>
                </div>
            </div>

            <div class="space-y-2">
                <label for="loginPassword" class="block text-sm font-medium text-neutral-700">密码</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
              <i class="fa-solid fa-lock"></i>
            </span>
                    <input type="password" id="loginPassword" name="password"
                           class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                           placeholder="••••••••" required>
                    <button type="button" id="toggleLoginPassword" class="absolute inset-y-0 right-0 flex items-center pr-3 text-neutral-500 hover:text-neutral-700">
                        <i class="fa-solid fa-eye-slash"></i>
                    </button>
                </div>
            </div>

            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <input id="rememberMe" name="rememberMe" type="checkbox" class="h-4 w-4 rounded border-neutral-300 text-primary focus:ring-primary/50">
                    <label for="rememberMe" class="ml-2 block text-sm text-neutral-600">记住我</label>
                </div>
                <div class="text-sm">
                    <a href="#" class="font-medium text-primary hover:text-primary/80">忘记密码?</a>
                </div>
            </div>

            <button type="submit"
                    class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg btn-hover transition-all flex items-center justify-center">
                <i class="fa-solid fa-right-to-bracket mr-2"></i> 登录
            </button>
        </form>

        <div class="text-center text-sm text-neutral-600">
            没有账号? <button id="showRegisterBtn" class="font-medium text-primary hover:text-primary/80">注册</button>
        </div>
    </div>

    <!-- 注册表单 -->
    <div id="registerForm" class="p-8 md:p-10 space-y-8 hidden">
        <div class="text-center">
            <div class="text-[clamp(2rem,5vw,3rem)] text-primary mb-4">
                <i class="fa-solid fa-user-plus"></i>
            </div>
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-800">创建账户</h1>
            <p class="text-neutral-600 mt-2">填写以下信息注册新账户</p>
        </div>

        <form id="registerFormData" class="space-y-5">
            <div class="space-y-2">
                <label for="registerName" class="block text-sm font-medium text-neutral-700">姓名</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
              <i class="fa-solid fa-user"></i>
            </span>
                    <input type="text" id="registerName" name="username"
                           class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                           placeholder="请输入您的姓名" required>
                </div>
            </div>

            <div class="space-y-2">
                <label for="registerEmail" class="block text-sm font-medium text-neutral-700">邮箱</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
              <i class="fa-solid fa-envelope"></i>
            </span>
                    <input type="email" id="registerEmail" name="email"
                           class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                           placeholder="your@email.com" required>
                </div>
            </div>

            <div class="space-y-2">
                <label for="registerPassword" class="block text-sm font-medium text-neutral-700">密码</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
              <i class="fa-solid fa-lock"></i>
            </span>
                    <input type="password" id="registerPassword" name="password"
                           class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                           placeholder="至少8个字符" required>
                    <button type="button" id="toggleRegisterPassword" class="absolute inset-y-0 right-0 flex items-center pr-3 text-neutral-500 hover:text-neutral-700">
                        <i class="fa-solid fa-eye-slash"></i>
                    </button>
                </div>
            </div>

            <div class="space-y-2">
                <label for="registerConfirmPassword" class="block text-sm font-medium text-neutral-700">确认密码</label>
                <div class="relative">
            <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-500">
              <i class="fa-solid fa-lock"></i>
            </span>
                    <input type="password" id="registerConfirmPassword" name="confirmPassword"
                           class="w-full pl-10 pr-4 py-3 rounded-lg border border-neutral-300 input-focus transition-all"
                           placeholder="再次输入密码" required>
                </div>
            </div>

            <div class="flex items-start">
                <div class="flex items-center h-5">
                    <input id="terms" name="terms" type="checkbox" class="h-4 w-4 rounded border-neutral-300 text-primary focus:ring-primary/50" required>
                </div>
                <div class="ml-3 text-sm">
                    <label for="terms" class="text-neutral-600">我同意<a href="#" class="font-medium text-primary hover:text-primary/80">服务条款</a>和<a href="#" class="font-medium text-primary hover:text-primary/80">隐私政策</a></label>
                </div>
            </div>

            <button type="submit"
                    class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-3 px-4 rounded-lg btn-hover transition-all flex items-center justify-center">
                <i class="fa-solid fa-user-plus mr-2"></i> 注册
            </button>
        </form>

        <div class="text-center text-sm text-neutral-600">
            已有账号? <button id="showLoginBtn" class="font-medium text-primary hover:text-primary/80">登录</button>
        </div>
    </div>

    <!-- 欢迎页面 -->
    <div id="welcomePage" class="hidden p-8 md:p-10 space-y-8">
        <div class="text-center">
            <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-800">
                欢迎，<span id="usernameDisplay"></span>！
            </h1>
        </div>

        <div class="bg-white rounded-lg shadow-sm overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-neutral-200">
                    <thead class="bg-neutral-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">姓名</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">邮箱</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody id="userListBody" class="bg-white divide-y divide-neutral-200">
                    <!-- 用户数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>

        <button id="logoutBtn" class="w-full bg-red-500 hover:bg-red-600 text-white font-medium py-2 px-4 rounded-lg btn-hover transition-all flex items-center justify-center">
            <i class="fa-solid fa-right-from-bracket mr-2"></i> 退出登录
        </button>
    </div>
</div>

<script>
    // 等待DOM完全加载后再执行
    document.addEventListener('DOMContentLoaded', function() {
        // DOM 元素
        const loginForm = document.getElementById('loginForm');
        const registerForm = document.getElementById('registerForm');
        const welcomePage = document.getElementById('welcomePage');
        const loginFormData = document.getElementById('loginFormData');
        const registerFormData = document.getElementById('registerFormData');
        const showRegisterBtn = document.getElementById('showRegisterBtn');
        const showLoginBtn = document.getElementById('showLoginBtn');
        const toggleLoginPassword = document.getElementById('toggleLoginPassword');
        const toggleRegisterPassword = document.getElementById('toggleRegisterPassword');
        //const loginEmail = document.getElementById('loginEmail');
        const loginPassword = document.getElementById('loginPassword');
        const registerName = document.getElementById('registerName');
        const registerEmail = document.getElementById('registerEmail');
        const registerPassword = document.getElementById('registerPassword');
        const registerConfirmPassword = document.getElementById('registerConfirmPassword');
        //const welcomeName = document.getElementById('welcomeName');
        const logoutBtn = document.getElementById('logoutBtn');
        const userListContainer = document.getElementById('userListContainer');
        const userListBody = document.getElementById('userListBody');

        // 调试：检查元素是否找到
        console.log('userListContainer:', userListContainer);
        console.log('userListBody:', userListBody);

        // 切换登录和注册表单
        showRegisterBtn.addEventListener('click', () => {
            loginForm.classList.add('hidden');
            registerForm.classList.remove('hidden');
        });

        showLoginBtn.addEventListener('click', () => {
            registerForm.classList.add('hidden');
            loginForm.classList.remove('hidden');
        });

        // 切换密码可见性
        toggleLoginPassword.addEventListener('click', () => {
            const type = loginPassword.getAttribute('type') === 'password' ? 'text' : 'password';
            loginPassword.setAttribute('type', type);
            toggleLoginPassword.querySelector('i').classList.toggle('fa-eye');
            toggleLoginPassword.querySelector('i').classList.toggle('fa-eye-slash');
        });

        toggleRegisterPassword.addEventListener('click', () => {
            const type = registerPassword.getAttribute('type') === 'password' ? 'text' : 'password';
            registerPassword.setAttribute('type', type);
            toggleRegisterPassword.querySelector('i').classList.toggle('fa-eye');
            toggleRegisterPassword.querySelector('i').classList.toggle('fa-eye-slash');
        });

        // 注册表单提交
        registerFormData.addEventListener('submit', async (e) => {
            e.preventDefault();

            console.log("注册表单提交触发");

            // 清除之前的消息
            document.querySelectorAll('.bg-red-50, .bg-green-50').forEach(el => el.remove());

            // 验证密码是否匹配
            if (registerPassword.value !== registerConfirmPassword.value) {
                showError('密码不匹配');
                return;
            }

            // 验证必填字段
            if (!registerName.value || !registerEmail.value || !registerPassword.value) {
                showError('所有字段必须填写');
                return;
            }

            try {
                // 构造请求数据
                const formData = {
                    username: registerName.value,
                    email: registerEmail.value,
                    password: registerPassword.value
                };

                console.log("准备发送注册请求", formData);

                // 发送POST请求
                const response = await fetch('register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams(formData).toString()
                });

                console.log("收到响应状态:", response.status);

                if (!response.ok) {
                    const errorData = await response.json().catch(() => null);
                    throw new Error(errorData?.message || `HTTP错误! 状态码: ${response.status}`);
                }

                const data = await response.json();
                console.log("解析后的数据", data);

                if (data.success) {
                    showSuccess(data.message || '注册成功');
                    registerFormData.reset();
                    setTimeout(() => {
                        registerForm.classList.add('hidden');
                        loginForm.classList.remove('hidden');
                    }, 2000);
                } else {
                    showError(data.message || '注册失败');
                }
            } catch (error) {
                console.error("注册请求出错:", error);
                showError('注册失败: ' + (error.message || '服务器错误'));
            }
        });

        // 登录表单提交
        loginFormData.addEventListener('submit', async (e) => {
            e.preventDefault();

            // 构造请求数据
            const formData = {
                username: document.getElementById('loginName').value,
                password: loginPassword.value
            };

            try {
                console.log("准备发送登录请求", formData); // 调试

                // 发送 POST 请求
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams(formData).toString()
                });

                console.log("收到响应状态:", response.status); // 调试

                // 获取响应文本用于调试
                const responseText = await response.text();
                console.log("响应内容:", responseText); // 调试

                // 尝试解析JSON
                let data;
                try {
                    data = JSON.parse(responseText);
                } catch (e) {
                    console.error("JSON解析错误:", e);
                    throw new Error("服务器返回的数据不是有效的JSON格式");
                }

                console.log("解析后的数据:", data); // 调试

                if (data.success) {
                    // 登录成功，显示欢迎页面
                    console.log("登录成功，准备跳转"); // 调试
                    loginForm.classList.add('hidden');
                    welcomePage.classList.remove('hidden');
                    document.getElementById('usernameDisplay').textContent = data.user.username;
                    // 自动加载用户列表
                    await fetchUserList();
                } else {
                    showError(data.message || '登录失败');
                }
            } catch (error) {
                console.error("登录请求出错:", error); // 调试
                showError('登录失败: ' + error.message);
            }
        });

        // 退出登录
        logoutBtn.addEventListener('click', () => {
            welcomePage.classList.add('hidden');
            loginForm.classList.remove('hidden');
        });

        // 显示错误消息
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mt-4 relative';
            errorDiv.innerHTML = `
            <div class="flex items-center">
              <i class="fa-solid fa-exclamation-circle mr-2"></i>
              <p>${message}</p>
            </div>
            <button class="absolute top-2 right-2 text-red-400 hover:text-red-600">
              <i class="fa-solid fa-times"></i>
            </button>
          `;

            registerFormData.insertBefore(errorDiv, registerFormData.firstChild);

            // 关闭按钮
            const closeBtn = errorDiv.querySelector('button');
            closeBtn.addEventListener('click', () => {
                errorDiv.remove();
            });

            // 自动关闭
            setTimeout(() => {
                errorDiv.remove();
            }, 5000);
        }

        // 显示成功消息
        function showSuccess(message) {
            const successDiv = document.createElement('div');
            successDiv.className = 'bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg mt-4 relative';
            successDiv.innerHTML = `
            <div class="flex items-center">
              <i class="fa-solid fa-check-circle mr-2"></i>
              <p>${message}</p>
            </div>
            <button class="absolute top-2 right-2 text-green-400 hover:text-green-600">
              <i class="fa-solid fa-times"></i>
            </button>
          `;

            registerFormData.insertBefore(successDiv, registerFormData.firstChild);

            // 关闭按钮
            const closeBtn = successDiv.querySelector('button');
            closeBtn.addEventListener('click', () => {
                successDiv.remove();
            });

            // 自动关闭
            setTimeout(() => {
                successDiv.remove();
            }, 3000);
        }

        // 在DOMContentLoaded事件监听器中添加以下函数
        async function fetchUserList() {
            try {
                console.log("开始获取用户列表..."); // 调试
                const response = await fetch('/userList');

                console.log("响应状态:", response.status); // 调试
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }

                const users = await response.json();
                console.log("获取到的用户数据:", users); // 调试

                const userListBody = document.getElementById('userListBody');
                userListBody.innerHTML = ''; // 清空现有内容

                if (users && users.length > 0) {
                    // 动态创建表格行
                    users.forEach(user => {
                        const row = document.createElement('tr');
                        row.className = 'hover:bg-neutral-50';

                        // 创建单元格
                        const nameCell = document.createElement('td');
                        nameCell.className = 'px-6 py-4 whitespace-nowrap text-sm font-medium text-neutral-900';
                        nameCell.textContent = user.username || '无';

                        const emailCell = document.createElement('td');
                        emailCell.className = 'px-6 py-4 whitespace-nowrap text-sm text-neutral-500';
                        emailCell.textContent = user.email || '无';

                        // 添加到行
                        row.appendChild(nameCell);
                        row.appendChild(emailCell);

                        // 添加到表格
                        userListBody.appendChild(row);
                    });
                } else {
                    const emptyRow = document.createElement('tr');
                    emptyRow.innerHTML = `
                <td colspan="2" class="px-6 py-4 text-center text-sm text-neutral-500">
                    没有用户数据
                </td>
            `;
                    userListBody.appendChild(emptyRow);
                }
            } catch (error) {
                console.error("获取用户列表出错:", error);
                const userListBody = document.getElementById('userListBody');
                userListBody.innerHTML = `
            <tr>
                <td colspan="2" class="px-6 py-4 text-center text-sm text-red-500">
                    加载用户列表失败: ${error.message}
                </td>
            </tr>
        `;
            }
        }
    });
</script>
</body>
</html>